<?php
//同步商品热度数据到redis以及store.wiki.basic_goods_hot

use Biz\model\wiki\Wiki as mWiki;
use Biz\model\wiki\WikiBasic;
use Doraemon\pockets\config\IniConfig;
use Doraemon\tools\Log;
use Doraemon\tools\Presto\PrestoClientV2;
use Doraemon\tools\Presto\PrestoException;


ini_set('display_errors', 1);
error_reporting(E_ALL ^ E_NOTICE ^ E_WARNING ^ E_DEPRECATED);
ini_set('memory_limit', '1024M');
require_once '/data/wwwroot/g_vendor/autoload.php';

//更新品牌指数

syncBrandScore();

//数据是每天3点前跑完数据 定时任务目前是6点取数据
$basicIdMax = WikiBasic::get('id', ['LIMIT' => 1, 'ORDER' => ['id' => 'DESC']]);
$pageSize = 5000;

$page = ceil($basicIdMax / $pageSize);
// 初始化presto客户端
$config = IniConfig::getConfigSelect('presto', 'brand');
$presto = new PrestoClientV2("{$config['host']}:{$config['port']}/{$config['path']}", "hive", $config["username"],
    $config["password"]);
$i = 0;
try {
    while ($i < $page) {
        try {
            $start = $i * $pageSize;
            $end = ($i + 1) * $pageSize;
            $presto->Query("select id,wiki_score as score from oss.hhz.dwd_brand_wiki_score  where id >{$start} and  id<= {$end}");
            $presto->WaitQueryExec();
        } catch (PrestoException $e) {
            Log::error('同步商品热度数据异常'.$e);
        }
        $data = $presto->GetData();
        echo '这是第'.($i + 1).'批数据处理开始,共：'.(count($data)).'条数据'.PHP_EOL;
        Log::info('这是第'.($i + 1).'批数据处理开始,共：'.(count($data)).'条数据');
        if ($data) {
            foreach ($data as $row) {
                //更新商品热度缓存
                \Biz\cache\wiki\GoodsHot::setGoodsHotById($row[0],$row[1]);
                //更新数据库 store.wiki.basic_goods_hot
                mWiki::update(['basic_goods_hot' => $row[1]], ['basic_id' => $row[0], 'basic_goods_hot[!]' => $row[1]]);
            }
        }
        echo '这是第'.($i + 1).'批数据处理结束,共：'.(count($data)).'条数据被处理'.PHP_EOL;
        Log::info('这是第'.($i + 1).'批数据处理结束,共：'.(count($data)).'条数据被处理');
        $i++;
    }
} catch (Exception $exception) {
    Log::info('同步商品热度数据异常', ['exception' => $exception]);
}

//更新品牌指数
function syncBrandScore()
{
    $data = \Biz\model\brand\Brand::select('id',['id[>]'=>0]);
    if($data){
        foreach ($data as $brandId){
            $score = \Biz\cache\brand\BrandScoreCache::getBrandScore($brandId);
            \Biz\model\brand\Brand::update(['brand_score' => $score], ['id' => $brandId, 'brand_score[!]' => $score]);
        }
    }
}
